package com.siae.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;

import java.io.InputStream;

public class AliyunOSSUtils {
    /**
     AccessKey ID    LTAI5tFn8PLU5cTM3Qnz2NwU
     AccessKey Secret  QGVcjZWeD8wxPQKbjmRJSlQ8BLkefL
     */

    public static String uploadFile(InputStream input, String filename){
        // Endpoint以华东2（北京）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider defaultCredentialProvider =
                CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tFn8PLU5cTM3Qnz2NwU", "QGVcjZWeD8wxPQKbjmRJSlQ8BLkefL");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "y-wei-wei-wei";
        // 上传的文件的名称。
        String objectName = filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, defaultCredentialProvider);
        try {
            // 将文件传递给阿里的oss（Bucket名称，上传文件的名称，文件流）
            ossClient.putObject(bucketName, objectName, input);
            // 返回文件格式
            return "https://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+filename;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
